package cn.woo5.test.securitytest.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Autowired
  private RestAuthenticationSuccessHandler restSuccessHandler;

  @Autowired
  private RestAuthenticationFailureHandler restFailHandler;

  @Autowired
  private RestLogoutSuccessHandler logoutHandler;

  @Autowired
  private RestAuthenticationEntryPoint restEntryPoint;


  @Override
  protected void configure(final HttpSecurity http) throws Exception {
    http.authorizeRequests()
        .antMatchers("/swagger-ui.html", "/swagger-resources/**", "/v2/api-docs").permitAll()//
        .antMatchers("/api/ping").permitAll()//
        .antMatchers("/login").permitAll()//

        .antMatchers("/test").hasRole("STAFF")//

        .antMatchers("/api/staffs/{staffId}/**", "/api/luckydraw/{staffId}/**")
        .access("@webSecurity.checkUserId(authentication,#staffId)")//

        .anyRequest().denyAll();

    http.formLogin().loginProcessingUrl("/login");
    http.formLogin().successHandler(restSuccessHandler);
    http.formLogin().failureHandler(restFailHandler);
    http.exceptionHandling().authenticationEntryPoint(restEntryPoint);

    http.logout().logoutUrl("/logout").deleteCookies("remember-me");
    http.logout().logoutSuccessHandler(logoutHandler);

    http.rememberMe();
    http.csrf().disable();
  }

  @Override
  public void configure(final AuthenticationManagerBuilder auth) throws Exception {
    auth
        .inMemoryAuthentication()
        .withUser("user").password("password").roles("STAFF");
  }

}
